package cn.xlbweb.sso.filter;

import cn.xlbweb.sso.config.SsoPropertiesConfig;
import cn.xlbweb.sso.exception.SsoException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: bobi
 * @date: 2019-03-10 12:01
 * @description:
 */
@Component
@Slf4j
public class LoginFilter implements Filter {

    private final String VERIFY_TOKEN_RESULT = "true";

    @Autowired
    private SsoPropertiesConfig ssoPropertiesConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("sso LoginFilter init...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        // sso project id
        Integer projectId = ssoPropertiesConfig.getProjectId();
        if (projectId == null) {
            throw new SsoException("sso project id is null");
        }
        // sso server url
        String serverUrl = ssoPropertiesConfig.getServerUrl();
        if (serverUrl == null) {
            throw new SsoException("sso server url is null");
        }
        // 需要放行的url地址
        String[] excludeUris = ssoPropertiesConfig.getExcludeUris();
        if (excludeUris != null && excludeUris.length > 0) {
            for (String excludeUri : excludeUris) {
                if (excludeUri.equals(request.getRequestURI())) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }
        // 校验是否含有局部session
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (isLogin != null && isLogin) {
            filterChain.doFilter(request, response);
            return;
        }
        // 若请求链接中存在token参数
        String token = request.getParameter("token");
        if (StringUtils.isNotBlank(token)) {
            RestTemplate restTemplate = new RestTemplate();
            String clientUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            String url = ssoPropertiesConfig.getServerUrl() + "/verifyToken?token=" + token + "&clientUrl=" + clientUrl + "&jessionId=" + session.getId() + "&projectId=" + projectId;
            String result = restTemplate.getForObject(url, String.class);
            if (VERIFY_TOKEN_RESULT.equals(result)) {
                session.setAttribute("isLogin", true);
                filterChain.doFilter(request, response);
                return;
            }
        }
        // 跳转到sso server认证
        String redirectUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getRequestURI();
        response.sendRedirect(ssoPropertiesConfig.getServerUrl() + "/login?redirectUrl=" + redirectUrl);
    }

    @Override
    public void destroy() {
        log.info("sso LoginFilter destroy...");
    }
}
